package com.puman.watchtrade.fragment.info;

import java.text.BreakIterator;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.view.AbPlayView;
import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.fragment.info.adpter.ImgAdapter;
import com.puman.watchtrade.fragment.info.adpter.InfoListViewAdapter;
import com.puman.watchtrade.fragment.info.adpter.MyGallery;
import com.puman.watchtrade.fragment.info.httpHandler.InfoHttpHandler;
import com.puman.watchtrade.fragment.info.model.InfoDatas;
import com.puman.watchtrade.fragment.info.model.InfoImg;
import com.puman.watchtrade.fragment.info.model.InfoImgs;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.LoadingProgressDialog;

/*
 */
@SuppressLint({ "ValidFragment", "NewApi" })
public class InfoFregment extends Fragment {
	private View mView;

	/*
	 * init UI
	 */
	private AbPlayView mAbAutoPlayView = null;
	private ListView listView;
	private MyGallery gallery = null;
	private LinearLayout ll_focus_indicator_container = null;
	private ImageView imageView;
private TextView topImgTitle;
	/*
	 * init variable
	 */
	private LayoutInflater inflater;
	private InfoListViewAdapter infoListViewAdapter;
	private InfoDatas infoDatas = new InfoDatas();
	private InfoImgs infoImgs = new InfoImgs();
	public static final int GET_SUC = 0x1;
	public static final int GET_FAIL = 0x2;
	public static final int IMG_SUC = 0x3;
	public static final int IMG_FAIL = 0x4;
	private DataResult dataResult = new DataResult();
	private DataResult dataResultForImg = new DataResult();
	private ArrayList<String> imgList;
	private ArrayList<String> titleList;
	private ArrayList<ImageView> portImg;
	private InfoHttpHandler infoHttpHandler = new InfoHttpHandler();
	private int pageNumber = 1;
	private LoadingProgressDialog mProgress = null;
	/**
	 * 存储上一个选择项的Index
	 */
	private int preSelImgIndex = 0;

	public InfoFregment() {
		super();
	}

	public InfoFregment(MainActivity mainActivity) {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.info_layout, container, false);
		this.inflater = inflater;
		initView();
//		getTop();
		getInfoList();
		loadAnimation();
		return mView;
	}

	private void initView() {
		mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(
				MainActivity.getInstant().mySetOnClickListener);
		
		topImgTitle = (TextView) mView.findViewById(R.id.top_img_title);
		ll_focus_indicator_container = (LinearLayout) mView
				.findViewById(R.id.ll_focus_indicator_container);
	
		
		listView = (ListView) mView.findViewById(R.id.info_listview);
		infoListViewAdapter = new InfoListViewAdapter(getActivity(), infoDatas);
		listView.setAdapter(infoListViewAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
//				Log.i("curry", "info url:"+infoDatas.infoList.get(position).getUrl());
				InfoDetailFragment sellFragment = new InfoDetailFragment(infoDatas.infoList.get(position).getUrl(), 
							infoDatas.infoList.get(position).getPic(), "资讯与攻略");
				transaction.replace(R.id.main_non_bottom, sellFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
		});
	}
	
	private void loadAnimation(){
		AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
		// 设置动画执行的时间
		alphaAnimation.setDuration(1500);
		AnimationSet animationalpha = new AnimationSet(true);

		animationalpha.addAnimation(alphaAnimation);
		mView.findViewById(R.id.gallery).startAnimation(animationalpha);
		mView.findViewById(R.id.info_listview).startAnimation(animationalpha);
	}

	private void getInfoList() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
		.execute(topImgRunnable);
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(infolistRunnable);
	}

	/*
	 */
	Runnable infolistRunnable = new Runnable() {
		@Override
		public void run() {
			int what = GET_FAIL;
			dataResult = infoHttpHandler.InfoList(pageNumber + "");
			if (dataResult.flag) {
				what = GET_SUC;
			}
			sendMessage(what);
		}
	};
	
	/*
	 */
	Runnable topImgRunnable = new Runnable() {
		@Override
		public void run() {
			int what = IMG_FAIL;
			dataResultForImg = infoHttpHandler.topImg();
			if (dataResultForImg.flag) {
				what = IMG_SUC;
			}
			sendMessage(what);
		}
	};

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Gjfun.stopProgressDialog(mProgress);
			switch (msg.what) {
			case GET_SUC:
				infoDatas.infoList.clear();
				for (int i = 0; i < ((InfoDatas) dataResult.object).infoList
						.size(); i++) {
					infoDatas.infoList
							.add(((InfoDatas) dataResult.object).infoList
									.get(i));
				}
				if (infoDatas.infoList.size() == 0) {
					listView.setVisibility(View.GONE);
				}else {
					listView.setVisibility(View.VISIBLE);
				}
				infoListViewAdapter.notifyDataSetChanged();
				break;
			case GET_FAIL:
				listView.setVisibility(View.GONE);
				break;
			case IMG_SUC:
				infoImgs.imgList.clear();
				for (int i = 0; i < ((InfoImgs) dataResultForImg.object).imgList
						.size(); i++) {
					infoImgs.imgList
							.add(((InfoImgs) dataResultForImg.object).imgList
									.get(i));
//					Log.i("curry", "imageurl:"+infoImgs.imgList.get(i).getPic());
				}
				setTopImg();
				break;
			case IMG_FAIL:
				break;
			}
			return false;
		}
	};
	
	private void setTopImg(){
		imgList = new ArrayList<String>();
		titleList = new ArrayList<String>();
		for (int i = 0; i < infoImgs.imgList.size(); i++) {
			imgList.add(infoImgs.imgList.get(i).getPic());
			titleList.add(infoImgs.imgList.get(i).getTitle());
//			Log.i("curry", "imgList:"+imgList.get(i));
		}
		
		InitFocusIndicatorContainer();
		gallery = (MyGallery) mView.findViewById(R.id.gallery);
		gallery.setAdapter(new ImgAdapter(MainActivity.getInstant(), imgList, getActivity()));
		gallery.setFocusable(true);
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int selIndex, long arg3) {
				if (imgList.size() !=0) {
				selIndex = selIndex % imgList.size();
				// 修改上一次选中项的背景
				portImg.get(preSelImgIndex).setImageResource(
						R.drawable.ic_focus_select);
				// 修改当前选中项的背景
				portImg.get(selIndex).setImageResource(R.drawable.ic_focus);
				if (titleList.get(selIndex).length() > 15) {
					topImgTitle.setText(titleList.get(selIndex).substring(0, 15)+"...");
				}else {
					topImgTitle.setText(titleList.get(selIndex));
				}
				preSelImgIndex = selIndex;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int selIndex,
					long arg3) {
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				InfoDetailFragment sellFragment = new InfoDetailFragment(infoImgs.imgList.get(selIndex % imgList.size()).getUrl(),
						infoImgs.imgList.get(selIndex % imgList.size()).getPic(), "资讯与攻略");
				transaction.replace(R.id.main_non_bottom, sellFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
		});
	}
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	private void InitFocusIndicatorContainer() {
		portImg = new ArrayList<ImageView>();
		for (int i = 0; i < imgList.size(); i++) {
			ImageView localImageView = new ImageView(MainActivity.getInstant());
			localImageView.setId(i);
			ImageView.ScaleType localScaleType = ImageView.ScaleType.FIT_XY;
			localImageView.setScaleType(localScaleType);
			LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(
					24, 24);
			localImageView.setLayoutParams(localLayoutParams);
			localImageView.setPadding(5, 5, 5, 5);
			localImageView.setImageResource(R.drawable.ic_focus_select);
			portImg.add(localImageView);
			this.ll_focus_indicator_container.addView(localImageView);
		}
	}

}
